package com.shushan.util;

import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.widget.TextView;

import com.shushan.base.Constants;
import com.shushan.exam.bean.ExerciseBean;
import com.shushan.exam.bean.PaperBean;
import com.shushan.home.bean.ScoreAchieveBean;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName: StringTools
 * @Desciption: 字符串工具类
 * @author: yichaohua
 * @date: 2018-01-15
 */
public class StringTools {

    private static final String TAG = "StringTools";

    public static boolean isMobile(String mobile) {

        return Pattern.matches("^1\\d{10}$", mobile);
    }

    // 判断格式是否为email
    public static boolean isEmails(String email) {
        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);
        return m.matches();
    }
    public static boolean isNull(String str) {

        return (str == null) || (str.trim().length() == 0);
    }

    public static boolean isIdCard(String num) {

        if (isNull(num)) {
            return false;
        }

        if (num.length() == 18 || num.length() == 15) {
            return true;
        }

        return false;
    }

    public static String formatExamTime(int examTime){
        String minStr,secStr;
        int min = examTime / 60;
        int second = examTime % 60;

        if(min <= 0){
            minStr = "00";
        }else if(min < 10){
            minStr = "0" + min;
        }else {
            minStr = "" + min;
        }

        if(second <= 0){
            secStr = "00";
        }else if(second < 10){
            secStr = "0" + second;
        }else {
            secStr = "" + second;
        }

        return /*"用时 " + */minStr + ":" + secStr;
    }

    public static String formatTime(int examTime){
        String minStr,secStr;
        int min = examTime / 60;
        int second = examTime % 60;

        if(min <= 0){
            minStr = "00";
        }else if(min < 10){
            minStr = "0" + min;
        }else {
            minStr = "" + min;
        }

        if(second <= 0){
            secStr = "00";
        }else if(second < 10){
            secStr = "0" + second;
        }else {
            secStr = "" + second;
        }

        return minStr + ":" + secStr;
    }

    public static PaperBean getExerciseJsonBean(int examType, String data) {
        if(TextUtils.isEmpty(data)){
            return null;
        }

        PaperBean paperBean = new PaperBean();
        try {
            JSONObject jsonObject = new JSONObject(data);

            if(examType < 3){
                paperBean.initByJson(jsonObject);
            }else {
                JSONObject paperJson = jsonObject.optJSONObject("paper_info");
                if(paperJson != null){
                    paperBean.id = paperJson.optInt("id",0);
                    paperBean.video_id = paperJson.optInt("video_id",0);
                    paperBean.special_id = paperJson.optInt("special_id",0);
                    paperBean.outline_id = paperJson.optInt("outline_id",0);
                }

                JSONArray jsonArray = jsonObject.optJSONArray("paper");
                if(jsonArray != null){
                    for (int i = 0;i < jsonArray.length();i++){
                        JSONObject json = jsonArray.optJSONObject(i);
                        int subject_id = json.optInt("subject_id",0);

                        ExerciseBean exerciseBean = new ExerciseBean();
                        exerciseBean.initByJson(json);
                        switch (subject_id){
                            case Constants.SUBJECT_CHINESE_ID:
                                paperBean.chineseAdd(exerciseBean);
                                break;
                            case Constants.SUBJECT_MACH_ID:
                                paperBean.mathAdd(exerciseBean);
                                break;
                            case Constants.SUBJECT_ENGLISH_ID:
                                paperBean.englishAdd(exerciseBean);
                                break;
                            default:
                                break;

                        }
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }

        return paperBean;
    }

    public static boolean pswValide(String psw){
        if(TextUtils.isEmpty(psw)){
            return false;
        }
        if(psw.length() < 6){
            return false;
        }else if(psw.length() == 6){
            if(psw.equals(SharedPreferencesUtils.getStringDate(Constants.PARENT_PASSWD_SHAREPREFERS_KEY))){
                return true;
            }
        }
        return false;
    }

    public static String formatTime(int hour,int min){
        String hours,mins;
        if(hour < 10){
            hours = "0" + hour;
        }else {
            hours = hour + "";
        }

        if(min < 10){
            mins = "0" + min;
        }else {
            mins = min + "";
        }

        return (hours + ":" + mins);
    }

    public static String formatSecondTime(int seconds){
        int min = seconds / 60;
        int second = seconds % 60;

        if(min == 0 && second == 0){
            return "0秒";
        }

        return (min>0?(min+"分"):"") + (second>0?(second+"秒"):"");
    }

    public static String toDateStr(int num){
        if(num < 10){
            return ("0" + num);
        }

        return (num + "");
    }

    public static boolean same(String word,String sen){
        if(TextUtils.isEmpty(word) || TextUtils.isEmpty(sen)){
            return false;
        }

        String words = word.toLowerCase();
        String sens = sen.toLowerCase();

        if (words.equals(sens) || pluralize(words).equals(sens) || sens.startsWith(words)){
            return true;
        }

        return false;
    }

    public static String pluralize(String word){
        String plural  = "";
        if (word.endsWith("y")) {
//                         a)以辅音字母y结尾，则将y改成i，再加es；
            plural = word.substring(0, word.length() - 1) + "ies";//
        }
//                 b)以s，x，ch，sh结尾，则加es；c)以元音o结尾，则加es；
        else if (word.endsWith("o") || word.endsWith("s") || word.endsWith("x")
                || word.endsWith("ch") || word.endsWith("sh")) {
            plural = word + "es";
        } else {
            plural = word + "s";
        }

        return plural;
    }

    public static void setSpan(String word, String sentence, int color,TextView textView) {
        if(TextUtils.isEmpty(word) || TextUtils.isEmpty(sentence) || textView == null
                || sentence.length() < word.length()){
            return;
        }

        String[] wordArray = word.split("\\s+");

        int start = 0;
        int len = 0;
        String[] array = sentence.split("(\\s|[.,?;!:])+");
        for (int i = 0; i < array.length;i++){
            String str = array[i];
            if(wordArray.length > 1){
                if(same(wordArray[0],str)){
                    start += i;
                    len = str.length() + wordArray.length - 1;
                    for (int j = 1;j < wordArray.length;j++){
                        len += array[i+j].length();
                    }
                    break;
                }
            }else if(same(word,str)){
                start += i;
                len = str.length();
                break;
            }

            start += str.length();
        }

        if(len <= 0){
            textView.setText(sentence);
        }else {
            SpannableString spanString = new SpannableString(sentence);
            ForegroundColorSpan span = new ForegroundColorSpan(color);
            spanString.setSpan(span, start>0?start-1:0, start+len, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            textView.setText(spanString);
        }
    }

    /**
     * 获取指定url中的某个参数
     * @param url
     * @param key
     * @return
     */
    public static String getUrlParam(String url,String key){
        if(TextUtils.isEmpty(url) || TextUtils.isEmpty(key)){
            return "";
        }

        url += "&";
        String pattern = "(\\?|&){1}" + key + "=[\u4e00-\u9fa5_a-zA-Z0-9+/%]*(&{1})";

        Pattern r = Pattern.compile(pattern);

        Matcher m = r.matcher(url);
        if (m.find( )) {
            return m.group(0).split("=")[1].replace("&", "");
        } else {
            return "";
        }
    }

    public static String formatAmount(String amount){
        String result = "0.00";
        if(TextUtils.isEmpty(amount)){
            return result;
        }

        Log.i(TAG,"amount=" + amount);
        result = String.format("%.2f", Double.parseDouble(amount));

        Log.i(TAG,"result=" + result);
        return result;
    }

    public static String appendMmobile(String url){
        if (TextUtils.isEmpty(url)){
            return "";
        }

        String mobileUrl;
        String phone = SharedPreferencesUtils.getStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY);
        if(url.contains("?")){
            mobileUrl = url + "&phone=" + phone;
        }else {
            mobileUrl = url + "?phone=" + phone;
        }

        return mobileUrl;
    }
}
